07. Removing Geofences

KOTLIN PART2 L4 A07 Removing Geofences

When you no longer need geofences, it is the best practice to remove them in order to save battery and CPU cycles to stop monitoring.

  1. In HuntMainActivity.kt, copy this code into the removeGeofences() method:
private fun removeGeofences() {
   if (!foregroundAndBackgroundLocationPermissionApproved()) {
       return
   }
   geofencingClient.removeGeofences(geofencePendingIntent)?.run {
       addOnSuccessListener {
           Log.d(TAG, getString(R.string.geofences_removed))
           Toast.makeText(applicationContext, R.string.geofences_removed, Toast.LENGTH_SHORT)
               .show()
       }
       addOnFailureListener {
           Log.d(TAG, getString(R.string.geofences_not_removed))
       }
   }
}
  • Initially, check if foreground permissions have been approved, if they have not then return.
if (!foregroundAndBackgroundLocationPermissionApproved()) {
       return
   }
  • Call removeGeofences() on the geofencingClient and pass in the geofencePendingIntent.
geofencingClient.removeGeofences(geofencePendingIntent)?.run {

}
  • Add an onSuccessListener(), update the user that the geofences were successfully removed through a toast.
addOnSuccessListener {
   Log.d(TAG, getString(R.string.geofences_removed))
   Toast.makeText(applicationContext, R.string.geofences_removed, Toast.LENGTH_SHORT)
       .show()
}
  • Add an onFailureListener() where you log that the geofences weren’t removed.
addOnFailureListener {
   Log.d(TAG, getString(R.string.geofences_not_removed))
}